<template>
  <div>
    <van-pull-refresh success-duration="1500" :success-text="tipText" v-model="refreshIsLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error"
        error-text="请求失败，点击重新加载">
        <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
        <ArticleItem :article="item" v-for="item in list" :key="item.art_id + ''" :title="item.title"></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import ArticleItem from '@/components/sg-ui/article-item.vue'
export default {
  data () {
    return {
      // 渲染页面的列表数据
      list: [],
      // 加载中的状态
      loading: false,
      // 是否加载完成
      finished: false,
      // 时间戳
      pre_timestamp: Date.now(),
      error: false,
      refreshIsLoading: false, // 下拉刷新,
      tipText: null
    }
  },
  props: {
    channeId: {
      type: Number,
      required: true
    }
  },
  methods: {
    async onLoad () {
      // 1.发送请求获取数据
      try {
        const res = await getArticleList({
          channel_id: this.channeId,
          timestamp: Date.now(), // 获取的是第一页数据：传当前时间戳
          with_top: 0
        })
        // 2.将获取的数据存到list
        // this.list = res.data.data.results
        this.list.push(...res.data.data.results)
        // 保存时间戳
        this.pre_timestamp = res.data.data.pre_timestamp
        // 3.关闭当前这一次的加载状态，才会加载下一次的请求
        this.loading = false
        // 4.数据全部加载完成
        if (res.data.data.results.length === 0) {
          this.finished = true
        }
      } catch (err) {
        // 开启错误信息
        this.error = true
        // 关闭加载状态
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channeId,
          timestamp: Date.now(), // 获取的是第一页数据（最新数据)：传当前时间戳
          with_top: 0
        })
        this.list.unshift(...res.data.data.results)
        this.refreshIsLoading = false
        this.tipText = '共加载了' + res.data.data.results.length + '条数据'
      } catch (err) {
        this.refreshIsLoading = false
        this.tiptext = '加载失败'
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {
    ArticleItem
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.article_list {
  height: 80vh;
  overflow-y: scroll;
}
</style>
